package com.maixy.shorturldemo.utils;

/**
 * @ClassName ChangeBaseUtils
 * @Description TODO
 * @Date 2021/7/1 19:27
 * @Author maixingyu
 */
public class ChangeBaseUtils {

    /**
     * 十进制装换为62进制
     * @param num
     * @return
     */
    public static String radix10To62(long num) {
        if (num < 0) {
            throw new IllegalArgumentException("must be non-negative: " + num);
        }
        final int radix = 62;
        char[] outs = new char[64];
        int outsIndex = outs.length;
        long quotient;
        long remainder;
        char c;
        do {
            quotient = num / radix;
            remainder = num % radix;
            if (remainder <= 9) {
                c = (char) ('0' + remainder);
            } else if (remainder <= 10 + 26 - 1) {
                c = (char) ('a' + (remainder - 10));
            } else {
                c = (char) ('A' + (remainder - 36));
            }
            outs[--outsIndex] = c;
            num = quotient;
        } while (num > 0);
        return new String(outs, outsIndex, outs.length - outsIndex);
    }

    public static long radix62To10(String num) {
        int length = num.length();
        long out = 0;
        for (int i = 0; i < length; i++) {
            final char c = num.charAt(i);
            int charNum;
            if (c >= '0' && c <= '9') {
                charNum = c - '0';
            } else if (c >= 'a' && c <= 'z') {
                charNum = c - 'a' + 10;
            } else if (c >= 'A' && c <= 'Z') {
                charNum = c - 'A' + 10 + 26;
            } else {
                throw new IllegalArgumentException("invalid radix62 char: " + c);
            }
            out = out * 62 + charNum;
        }
        return out;
    }
}
